package br.com.srv.util;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

/**
 * <p>
 * Description: Classe auxiliar para tratamento de XML.
 * </p>
 * 
 */

public class XmlHelper {
	public static String readNode(String xml, String path) throws Exception {
		String pathVet[] = path.substring(1).split("/");
		SAXBuilder sb = new SAXBuilder();
		Document document = sb.build(new StringReader(xml));
		Element root = document.getRootElement();

		/*
		 * Percorre o vetor pulando o elemento root
		 */
		for (int i = 1; i < pathVet.length; i++) {
			root = root.getChild(pathVet[i]);
		}
		return root.getValue();
	}

	public static List parseList(String xml, String path, String element) throws Exception {
		String pathVet[] = path.substring(1).split("/");
		SAXBuilder sb = new SAXBuilder();
		Document document = sb.build(new StringReader(xml));
		Element root = document.getRootElement();

		/*
		 * Percorre o vetor pulando o elemento root
		 */
		for (int i = 1; i < pathVet.length; i++) {
			root = root.getChild(pathVet[i]);
		}

		/*
		 * Cria a nova lista.
		 */
		ArrayList result = new ArrayList(0);

		/*
		 * Percorre a lista de elementos.
		 */
		if (root != null) {
			List elements = root.getChildren();
			for (Iterator iter = elements.iterator(); iter.hasNext();) {
				Element node = (Element) iter.next();
				if (node.getName().equals(element)) {
					List children = node.getChildren();
					HashMap map = new HashMap(children.size());
					for (Iterator iterator = children.iterator(); iterator.hasNext();) {
						Element child = (Element) iterator.next();
						if (child.getName().equals("DIR")) {
							map.put(child.getName(), Util.getDirecao(child.getValue()));
						} else {
							map.put(child.getName(), child.getValue());
						}
					}
					result.add(map);
				}
			}
			result.trimToSize();
		}
		return result;
	}
}
